package com.lrm.biz.impl;

import com.lrm.biz.ITagBiz;
import com.lrm.dao.TagJPA;
import com.lrm.exception.MyException;
import com.lrm.pojo.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2017/11/30.
 * @Modified By:
 */
@Service
@Transactional
public class TagBizImpl implements ITagBiz {

    @Autowired
    private TagJPA tagJPA;
    @Override
    public Tag saveTag(Tag tag) {
        Tag save = tagJPA.save(tag);
        return save;
    }

    @Override
    public Tag getTag(Long id) {
        return tagJPA.findOne(id);
    }

    @Override
    public Page<Tag> pagelistTag(Pageable pageable) {
        Page<Tag> all = tagJPA.findAll(pageable);
        return all;
    }

    @Override
    public List<Tag> listTag(Integer size) {
        Sort sort =new Sort(Sort.Direction.DESC,"blogs.size");
        Pageable pageable =new PageRequest(0,size,sort);
        List<Tag> tags = tagJPA.listTag(pageable);
        return tags;
    }

    @Override
    public Tag upadtaTag(Long id, Tag tag) {
        Tag TagJPAOne = tagJPA.getOne(id);
        if (TagJPAOne==null) {
            throw new MyException("不存在该类型",2);
        }
        BeanUtils.copyProperties(TagJPAOne,tag);
        Tag save = tagJPA.save(TagJPAOne);
        return save;
    }

    @Override
    public Boolean delTag(Long id) {
        try {
            tagJPA.delete(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Tag findByname(String name) {
        Tag byName = tagJPA.findByName(name);
        return byName;
    }

    @Override
    public List<Long> convertToList(String ids) {
        List<Long> listid = new ArrayList<>();
        if (ids!=null&&!"".equals(ids)) {
            String[] split = ids.split(",");
            for (String s : split) {
                listid.add(Long.parseLong(s));
            }
        }
        return listid;
    }

    @Override
    public List<Tag> listList(String ids) {
        List<Tag> all = tagJPA.findAll(convertToList(ids));
        return all;
    }

}
